<?php

namespace app\controller\adminapi;

use chillerlan\QRCode\QRCode;
use hiduoke\controller\BaseController;
use think\facade\Cache;
use think\facade\Filesystem;

/**
 * Class Common 公共控制器
 * @package app\controller\adminapi
 * User: liuhongbin
 * Date: 2021-06-23 12:35
 */
class Common extends BaseController
{

    protected $notLogin = ['qr', 'getPluginJs', 'getIcons','getTemplateHooks'];

    /**
     * 上传
     */
    public function upload()
    {
        $disks = array('local', 'public', 'cert');
        $path = input('path', 'other'); //上传目录
        $disk = input('disk', 'local'); //上传位置
        if (!in_array($disk, $disks)) {
            $this->error('上传位置错误,检查disk参数是否为local，public，cert');
        }
        $file = $this->request->file('file');
        $saveName = Filesystem::disk($disk)->putFile($path, $file);
        return $this->success('上传成功', $saveName);
    }

    public function getLink($plaid = 0)
    {
        $addon_name = get_addon();
        $event_url = event($addon_name . "_addon_url", [])[0] ?? [];
        return $this->success("ok", $event_url);
    }

    /**
     * 获取地址
     */
    public function getLinkInput($plaid = 0)
    {
        function c_url($title, $url, $arr = [])
        {
            return array_merge(['title' => $title, 'url' => $url], $arr);
        }

        //系统地址
        $url = array(
            array(
                'group_name' => "系统链接",
                'children'   => array(
                    [
                        'title'    => '常用地址',
                        'children' => [
                            c_url("返回上一页", 'javascript :history.back(-1)'),
                        ]
                    ],
                    [
                        'title'    => '系统内置(测试版)',
                        'children' => [
                            c_url("个人中心", url("/h5/user", ['p' => $plaid])->build()),
                            c_url("用户钱包", url("/h5/wallet", ['p' => $plaid])->build()),
                            c_url("用户卡券", url("/h5/coupon", ['p' => $plaid])->build()),
                        ]
                    ]
                )
            )
        );
        $event_url = event("system_create_url", []);
        return $this->success("ok", ['system' => $url, 'addons' => $event_url]);
    }

    public function getIcons($query, $limit = 100)
    {
        $api = "https://api.iconify.design/search?query=" . $query;
        $res = file_get_contents($api);
        $res = json_decode($res, true);
        return $this->success("ok", $res['icons']);
    }

    /**
     * 获取二维码
     */
    public function qr()
    {
        $data = input('data', '');
        $size = input('size', 5);
        $margin = input('margin', 2);
        $level = input('level', 'H');
        switch ($level) {
            case 'L':
                $level = QRCode::ECC_L;
                break;
            case 'M':
                $level = QRCode::ECC_M;
                break;
            case 'Q':
                $level = QRCode::ECC_Q;
                break;
            case 'H':
                $level = QRCode::ECC_H;
                break;
            default:
                $level = QRCode::ECC_H;
        }
        return make_code($data, $size, $margin, $level);
    }

    /**
     * 清理
     * @param string $type
     * @param string $key
     */
    public function clear($type = 'cache')
    {
        if ($type == 'cache') {
            Cache::clear();
        }
        return $this->success("清理成功");
    }

    public function getTemplateHooks()
    {
        // 定义需要获取的hooks列表
        $hooks = ['customer_menu_hook', 'header_user_left_hook', 'header_user_right_hook'];
        $result = [];

        // 清理dkSys参数，移除潜在危险内容
        $clean_dkSys = $this->cleanDkSys(input('dkSys', []));

        foreach ($hooks as $hook) {
            $event = event($hook, $clean_dkSys);
            $stringData = '';
            $arrayData = [];

            foreach ($event as $hookResult) {
                if (is_string($hookResult)) {
                    // 如果是字符串，拼接HTML
                    $stringData .= $this->sanitizeHookOutput($hookResult);
                } elseif (is_array($hookResult)) {
                    // 如果是数组，合并数组
                    $arrayData = array_merge($arrayData, $hookResult);
                }
            }

            // 优先使用字符串数据，如果没有字符串数据则使用数组数据
            if (!empty($stringData)) {
                $result[$hook] = $stringData;
            } elseif (!empty($arrayData)) {
                $result[$hook] = $arrayData;
            } else {
                $result[$hook] = '';
            }
        }

        return $this->success('', $result);
    }


    /**
     * 获取页面的hook
     */
    public function getTemplateHooksOld()
    {
        // 参数验证
        $hooks = input('hooks', []);
        $dkSys = input('dkSys', []);

        // 确保hooks是数组
        if (!is_array($hooks)) {
            return $this->error('hooks参数必须是数组');
        }

        // 白名单验证，只允许预定义的hook
        $allowed_hooks = array(
            'header_user_right_hook',
            'header_user_left_hook',
        );

        // 过滤和验证hook名称
        $valid_hooks = [];
        foreach ($hooks as $hook) {
            // 确保hook是字符串且在白名单中
            if (is_string($hook) && in_array($hook, $allowed_hooks)) {
                $valid_hooks[] = $hook;
            }
        }

        if (empty($valid_hooks)) {
            return $this->success('', []);
        }

        // 清理dkSys参数，移除潜在危险内容
        $clean_dkSys = $this->cleanDkSys($dkSys);

        $data = [];
        foreach ($valid_hooks as $hook) {
            $event = event($hook, $clean_dkSys);
            $data[$hook] = '';
            foreach ($event as $result) {
                // 对hook结果进行安全处理
                if (is_string($result)) {
                    $data[$hook] .= $this->sanitizeHookOutput($result);
                }
            }
        }

        return $this->success('', $data);
    }

    public function getCustomerMenu()
    {
        $customerMenu = event('customer_menu_hook');
        $data = [];
        foreach ($customerMenu as $key => $value) {
            $data = array_merge($data, $value);
        }
        return $this->success('', $data);
    }

    /**
     * 清理dkSys参数
     * @param array $dkSys
     * @return array
     */
    private function cleanDkSys($dkSys)
    {
        if (!is_array($dkSys)) {
            return [];
        }

        $cleaned = [];
        foreach ($dkSys as $key => $value) {
            // 只允许字符串和数字类型的值
            if (is_string($value) || is_numeric($value)) {
                $key = preg_replace('/[^a-zA-Z0-9_]/', '', $key); // 清理键名
                $cleaned[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
            }
        }

        return $cleaned;
    }

    /**
     * 清理hook输出内容
     * @param string $output
     * @return string
     */
    private function sanitizeHookOutput($output)
    {
        if (!is_string($output)) {
            return '';
        }

        // 移除危险内容
        $output = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/mi', '', $output);
        $output = preg_replace('/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/mi', '', $output);
        $output = preg_replace('/on\w+\s*=\s*["\'][^"\']*["\']/', '', $output);
        $output = preg_replace('/javascript\s*:/i', '', $output);

        return $output;
    }



    public function getPluginJs()
    {
        $dkSys = input('dkSys', []);
        $js = event('insert_addon_js', $dkSys);
        $data = [];
        foreach ($js as $key => $value) {
            $data = array_merge($data, $value);
        }
        return $this->success('', $data);
    }
}
